#include "createtable.h"

CreateTable::CreateTable()
{

}

CreateTable::~CreateTable()
{

}

/**
* \brief Input function to read an opened file.
* \brief Wrong filepath input results into an error.
* \brief If opening an incorrect file and error will be displayed.
* \param data = "data" is a pointer to the struct
* \param pName = "pName" is a character pointer to an array containing the total amount of characters that will be read.
* \return Returns 0. Breaks out of function and goes back to main menu.
* \return Returns 1. Continues the following procedures.
*/
int CreateTable::InputUserDataFromFile(struct UserData& data, string& sName)
{
    FILE *fp; //File pointer
    string sfnamer;		//Is an array of characters used for the filename. This is for Storing File Path/Name of Image to Display
    cout << endl << endl << "Please Enter the Full Path of the Image file you want to view: " << endl;
    cin >> sfnamer;
    fp=fopen(sfnamer.c_str(),"rb");

    if(fp==NULL)
	{
        cout << endl << sfnamer << " [ERROR: FILE NOT FOUND!]" << endl << endl << endl;
		getch();
		return 0;
	}
	else
    {
        int i = 0; //Counter counts all characters in the string.
        fseek(fp, 0, SEEK_SET); //Sets the position indicator associated with the stream to a new position
        char readchar = 'x'; //Read characters. x is used for comparison against \n. There must be something to compare to

        while(readchar != '\n') //if readchar == \n then the loop will stop and the name has been read
        {
            fread(&readchar, sizeof(readchar), 1, fp);
            sName[i] = readchar; //the total amount of characters that will be read
            i++;
        }
        i = 0;
        readchar = 'x';
        string Numstring; //A string of characters containing the total amount of characters that will be read in the weight input.
        while(readchar != '\n')
        {
            fread(&readchar, sizeof(char), 1, fp);
            Numstring[i] = readchar;
            i++;
        }
        i=0;
        data.iweight = atoi(Numstring.c_str());
        readchar = 'x';
        string Numstring2; //A string of characters containing the total amount of characters that will be read in the lenght input.
        while(readchar != '\n' && !feof(fp)) //feof means File, End Of File, it will return a positive number(true) when the file is not at the end, and a negative number (false) when it is, this way, the while loop will end when the file reaches the end.
        {
            fread(&readchar, sizeof(char), 1, fp);
            Numstring2[i] = readchar;
            i++;
        }
        data.flenght = atof(Numstring2.c_str());

        if(data.iweight < MINWEIGHT_KG || data.iweight > MAXWEIGHT_KG || data.flenght < MINLENGHT_M || data.flenght > MAXLENGHT_M)
        {
            cout << endl << "[ERROR: WEIGHT INPUT NOT ACCEPTED BECAUSE THE INPUT IS INCORRECT!]";
            cout << endl << "[PLEASE TRY AGAIN.]" << endl;
            InputUserData(data); //Manual data input
        }
        fclose(fp);
    }
    return 1;
}

/**
* \brief Function to save a file.
* \brief If the filepath is excepted the data will be put in "psavedarray" which functions as a pointer.
* \param pSavedArray = "psavedarray" is a pointer. data will be saved in an array.
* \param i = Character counter counts the amount of characters that needs to be saved.
*/

void CreateTable::savetofile(string sSaveString)
{
    int SOpt; //The save option of choice
    cout << endl << "Do you want to save it to a file?";
    cout << endl << "Option 1: Yes";
    cout << endl << "Option 2: No";
    cout << endl << endl << "Insert number of choice: ";
    cin >> SOpt;

    if (SOpt == 1)
    {
        //save
        FILE *fp; //File pointer
        string sfnamer;		//Is an array of characters used for the filename. This is for Storing File Path/Name of file
        cout << endl << endl << "Please Enter the Full Path of the Image file you want to save to: " << endl;
        cin >> sfnamer;
        fp=fopen(sfnamer.c_str(),"wb");

        if(fp==NULL)
        {
            cout << endl << sfnamer << " [ERROR: FILE NOT SAVED!]" << endl << endl << endl;
            getch();
        }
        else
        {
            fwrite(sSaveString.c_str(), sizeof(char), sSaveString.size(),fp);
            fclose(fp);
            cout << endl << "[FILE SAVED]" << endl << endl << endl;
        }
    }
}

/**
* \brief Input function for weight steps input.
* \brief Input thats lower then the minimum or higher then maximum will get and error message.
* \param piSteps = "pisteps" is a pointer. steps is the weight steps in kilograms.
* \param piEndweigt = "piendweight" is a pointer. the last weight value to calculate to.
* \param iweight = Input weight in kilograms. weight is declared in the struct data.
*/
bool CreateTable::InputWeightSteps(int& iSteps, int& iEndweight, int iWeight)
{
    while(iSteps < MINSTEPS_KG || iSteps > MAXSTEPS_KG)
    {
        cout << endl << "Insert a weight step size from 1kg to 10kg: ";
        cin >> iSteps;


        if(iSteps < MINSTEPS_KG || iSteps > MAXSTEPS_KG)        {
            cout << endl << "[ERROR: WEIGHTSTEPS INPUT NOT ACCEPTED BECAUSE THE INPUT IS INCORRECT!]";
            cout << endl << "[PLEASE TRY AGAIN.]" << endl;
        }
    }
    while(iEndweight <= iWeight || iEndweight >  MAXENDWEIGHT_KG)
    {
       cout << endl << "Insert the end weight from 40kg to 170kg.";
       cout << endl << "This weight is the weight on which the quetelet index table will stop: ";
       cin >> iEndweight;


        if(iEndweight <= iWeight || iEndweight >  MAXENDWEIGHT_KG)
        {
           cout << endl << "[ERROR: ENDWEIGHT INPUT NOT ACCEPTED BECAUSE THE INPUT IS INCORRECT!]";
                   cout << endl << "[PLEASE TRY AGAIN.]";
        }
    }
    return true;
}

/**
* \brief This creates a table with calculated  quetelet index results depending on the user/file input.
* \param pName = This pointer contains the name input data
* \param data = "data" is a pointer to the struct
* \param isteps = Integer representing the amount of weight steps in kiligrams to create a table.
* \param iLastCalWeight = Integer representing the last weight to calculate to.=
*/
void  CreateTable::CreateQueteletIndexTable(string const& sName, struct UserData& data, int iSteps, int iLastCalWeight)
{
    stringstream ss(stringstream::in | stringstream::out);

    ss << "=====================================================" << endl;
    ss << "Name: "<< sName << endl << endl;
    ss << "Weight:  | Lenght: | Quetelet Index: | Verdict:" << endl;
    ss << "---------|---------|------------------|--------------" << endl;
    while(data.iweight <= iLastCalWeight) //The endweight will be shown in the table
    {
        float QIndex = QueteletIndexCalculation(data);
        string sQueteletIndex;
        ConvertQueteletIndexToString(QIndex, sQueteletIndex);
        ss.width(6);
        ss.flags(std::ios::right);
        ss << data.iweight ;
        ss << "   |";
        ss.width(6);
        ss.flags(std::ios::right);
        ss << fixed << setprecision(2) << data.flenght;
        ss << "   |";
        ss.width(10);
        ss.flags(std::ios::right);
        ss << fixed << setprecision(1) << QIndex;
        ss << "        |";
        ss << sQueteletIndex << endl;
        data.iweight += iSteps;
    }
    ss << endl;

    cout << ss.str();

    savetofile(ss.str());
}



